package io.wdb.modules.generator.generator.service.impl;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import io.wdb.common.utils.DateFormatUtil;
import io.wdb.common.utils.DateUtils;
import io.wdb.common.utils.ExcelReadUtil;
import io.wdb.modules.generator.generator.dao.BookInfoDao;
import io.wdb.modules.generator.generator.dao.BookReadableDao;
import io.wdb.modules.generator.generator.dao.BookRecommendationDao;
import io.wdb.modules.generator.generator.dao.BookTopicalDao;
import io.wdb.modules.generator.generator.dao.BookTopicalMappingsDao;
import io.wdb.modules.generator.generator.entity.BookInfoEntity;
import io.wdb.modules.generator.generator.entity.BookReadableEntity;
import io.wdb.modules.generator.generator.entity.BookRecommendationEntity;
import io.wdb.modules.generator.generator.entity.BookTopicalEntity;
import io.wdb.modules.generator.generator.entity.web.ResponseEnum;
import io.wdb.modules.generator.generator.entity.web.WebResponse;
import io.wdb.modules.generator.generator.service.UpDownLoadFileService;

@Service
public class UpDownLoadFileServiceImpl implements UpDownLoadFileService{
	
	private Logger logger = LoggerFactory.getLogger(UpDownLoadFileServiceImpl.class);
	
	@Autowired
	private BookTopicalMappingsDao bookTopicalMappingsDao;
	
	@Autowired
	private BookTopicalDao bookTopicalDao;
	
	@Autowired
	private BookInfoDao bookInfoDao;
	
	@Autowired
	private BookReadableDao bookReadableDao;
	
	@Autowired
	private BookRecommendationDao bookRecommendationDao;
	
	@Value("${wdb007.upload.path}")
	private String uploadPath;
	
	@Override
	public WebResponse analysisExcel(MultipartFile multipartFile) {
		WebResponse webResponse = new WebResponse();
		String dateStr = DateUtils.format(new Date());
		//判断目标目录是否存在
		File fileDir = new File(uploadPath+dateStr);
		this.judeDirExists(fileDir);
		//存储到服务器端的文件新名称
		String originalFileName = multipartFile.getOriginalFilename().replaceAll("-", "");  
		if(!(originalFileName.endsWith("xls")||originalFileName.endsWith("xlsx"))) {
			webResponse.setCode(ResponseEnum.FILE_FORMAT_ERROR.getCode());
			webResponse.setMessage(ResponseEnum.FILE_FORMAT_ERROR.getMessage());
			return webResponse;
		}
		String token = UUID.randomUUID().toString().replaceAll("-", "");
		String newFileName = "";
		try {
			String timeToken = "";
			//处理文件
			List<ArrayList<String>> list = new ExcelReadUtil().readExcel(multipartFile);  
			if(originalFileName.startsWith("bookinfo")) {
				timeToken = this.handleBookInfo(list,fileDir,token+originalFileName);
			}
			for(ArrayList<String> item:list) {
				for(String s:item) {
					System.out.print(s+"\t");
				}
				System.out.println();
			}
			//目标地址
			newFileName = token+"-"+timeToken.split("-")[1]+"-"+originalFileName;
			File file = new File(fileDir+"/"+newFileName);
			multipartFile.transferTo(file);
		} catch (IllegalStateException | IOException e) {
			webResponse.setCode(ResponseEnum.FILE_ANALYSIS_ERROR.getCode());
			webResponse.setMessage(ResponseEnum.FILE_ANALYSIS_ERROR.getMessage());
			logger.error(e.getMessage(),e);
		}
		webResponse.setCode(100);
		webResponse.setMessage(newFileName);
		return webResponse;
	}
	
	// 判断文件夹是否存在，不存在就创建
	private void judeDirExists(File file) {

		if (file.exists()) {
			if (file.isDirectory()) {
				logger.info("用户评论上传路径已经存在");
			} else {
				logger.info("the same name file exists, can not create dir");
			}
		} else {
			logger.info("目录已经存在，不用创建。。。。。。");
			file.mkdirs();
		}

	}
	/**
	 * 
	 * @Method:handleBookInfo
	 * @Description:
	 * @Time 2018年1月25日 下午2:04:12
	 * @author: Tom
	 * @param originalFileName 出错数据记录文件名
	 * @param fileDir 出错数据记录目录
	 * @throws IOException 
	 */
	private String handleBookInfo(List<ArrayList<String>> list, File fileDir, String originalFileName) throws IOException {
		Date date = new Date();
		Pattern p = Pattern.compile("\\s*|\t|\r|\n");
		String errorFileName = originalFileName.substring(0,32)+"-"+DateUtils.format(date, DateUtils.DATE_PATTERN_STRING)+"-"+originalFileName.substring(32,originalFileName.indexOf("."))+".txt";
		
		BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(new File(fileDir+"/"+errorFileName)));
		StringBuffer buffer = new StringBuffer();
		for(ArrayList<String> eachBookInfo : list) {
			try {
				String isbn = eachBookInfo.get(0).trim();
				if(isbn==null||isbn.equals("")) {
					continue;
				}
				BookInfoEntity bookInfoEntity = new BookInfoEntity();
				bookInfoEntity.setIsbnNo(eachBookInfo.get(0));
				bookInfoEntity.setBookName(eachBookInfo.get(1));
				bookInfoEntity.setAuthor(eachBookInfo.get(2));
				
				BookReadableEntity bookReadableEntity = new BookReadableEntity();
				bookReadableEntity.setIsbn(eachBookInfo.get(0));
				bookReadableEntity.setMinAge(Integer.valueOf(eachBookInfo.get(3).substring(0, eachBookInfo.get(3).indexOf("-"))));
				bookReadableEntity.setMaxAge(Integer.valueOf(eachBookInfo.get(3).substring(eachBookInfo.get(3).indexOf("-")+1).replaceAll("岁", "")));
				bookReadableEntity.setCreateTime(date);
				String tops = eachBookInfo.get(5);
				if(tops!=null&&!tops.equals("")) {
					for(String topical:tops.split(",")) {
						String topicalCode = bookTopicalMappingsDao.getTopicalByName(topical);
						BookTopicalEntity bookTopicalEntity = new BookTopicalEntity();
						bookTopicalEntity.setCreateTime(date);
						bookTopicalEntity.setIsbn(eachBookInfo.get(0));
						bookTopicalEntity.setTopicalCode(topicalCode);
						BookTopicalEntity bookTopicalEntityDb = bookTopicalDao.selectByIsbnCode(bookTopicalEntity);
						if(bookTopicalEntityDb==null) {
							bookTopicalDao.save(bookTopicalEntity);
						}else {
							continue;
						}
					}
				}
				bookInfoEntity.setPress(eachBookInfo.get(6));
				//TODO 出版时间格式化
				bookInfoEntity.setPublicationDate(DateFormatUtil.parseDatePattern(eachBookInfo.get(7), DateFormatUtil.DATE_PATTERN_LEAN));
				bookInfoEntity.setPrice(new BigDecimal(eachBookInfo.get(8).replace("￥", "")));
				if(eachBookInfo.get(12)!=null && !eachBookInfo.get(12).equals("")) {
					BookRecommendationEntity bookRecommendationEntityDb = bookRecommendationDao.queryObject(isbn);
					if(bookRecommendationEntityDb==null) {
						BookRecommendationEntity bookRecommendationEntity = new BookRecommendationEntity();
						bookRecommendationEntity.setCreateTime(date);
						bookRecommendationEntity.setIsbnNo(isbn);
						bookRecommendationEntity.setModifyTime(date);
						bookRecommendationEntity.setRecommendation(Integer.valueOf(eachBookInfo.get(12)));
						bookRecommendationEntity.setRecommendationer(eachBookInfo.get(11));
						bookRecommendationDao.save(bookRecommendationEntity);
					}else {
						bookRecommendationEntityDb.setModifyTime(date);
						bookRecommendationEntityDb.setRecommendation(Integer.valueOf(eachBookInfo.get(12)));
						bookRecommendationEntityDb.setRecommendationer(eachBookInfo.get(11));
						bookRecommendationDao.update(bookRecommendationEntityDb);
					}
				}
				// TODO 简介，编者推荐，星级
				bookInfoEntity.setBrief(eachBookInfo.get(9));//简介
				bookInfoEntity.setDescribe(eachBookInfo.get(10));//描述
				bookInfoEntity.setCreateTime(date);
				bookInfoEntity.setModifyTime(date);
				//由于关联数据是否存在不能严格确定，不能批量插入
				BookInfoEntity bookInfoEntityDb =bookInfoDao.queryObject(isbn);
				if(bookInfoEntityDb==null) {
					bookInfoDao.save(bookInfoEntity);
				}else {
					bookInfoDao.update(bookInfoEntity);
				}
				BookReadableEntity bookReadableEntityDb = bookReadableDao.getBookReadbaleByIsbn(isbn);
				if(bookReadableEntityDb==null) {
					bookReadableDao.insert(bookReadableEntity);
				}else {
					bookReadableEntity.setId(bookReadableEntityDb.getId());
					bookReadableDao.updateBookReadable(bookReadableEntity);
				}
			} catch (Exception e) {
				for (String s : eachBookInfo) {
					if (buffer.length() > 0) {
						buffer.append("|");
					}
					s=(s==null?"":s);
					buffer.append(s);
				}
				bufferedWriter.write(buffer.toString());
				bufferedWriter.newLine();
				bufferedWriter.flush();
				buffer=new StringBuffer();
				logger.error(e.getMessage(), e);
			}
			
		}
		return errorFileName;
	}
}
